package tencent

func myAtoi(s string) int {
	idx, sign := getIndexAndSign(s)
	tmp := int64(0)
	for i := idx; i < len(s); i++ {
		if s[i] < '0' || s[i] > '9' {
			break
		}
		tmp = tmp*10 + int64(s[i]-'0')
		if tmp >= (1 << 31) {
			break
		}
	}
	tmp = tmp * int64(sign)
	if tmp >= (1 << 31) {
		return (1 << 31) - 1
	} else if tmp <= -1*(1<<31) {
		return -1 * (1 << 31)
	}
	return int(tmp)
}

func getIndexAndSign(s string) (int, int) {
	for i := 0; i < len(s); i++ {
		switch s[i] {
		case '+':
			return i + 1, 1
		case '-':
			return i + 1, -1
		case ' ':
			break
		default:
			return i, 1
		}
	}
	return len(s), 1
}
